package com.f1ussh.common.config;

import com.f1ussh.common.result.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 马腾飞
 * @CreateTime: 2025-10-01
 * @Description: 通用转换工具类
 * @Version: 1.0
 */


public class ConvertUtils {

    /**
     * 单个对象转换
     */
    public static <T> T convert(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        try {
            T target = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new RuntimeException("对象转换失败: " + targetClass.getSimpleName(), e);
        }
    }

    /**
     * 列表转换
     */
    public static <T> List<T> convertList(List<?> sourceList, Class<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return new ArrayList<>();
        }
        return sourceList.stream()
                .map(source -> convert(source, targetClass))
                .collect(Collectors.toList());
    }

    /**
     * 分页数据转换
     */
    public static <T> PageResult<T> convertPage(PageResult<?> sourcePage, Class<T> targetClass) {
        if (sourcePage == null) {
            return null;
        }
        List<T> records = convertList(sourcePage.getRecords(), targetClass);
        return PageResult.of(
                sourcePage.getTotal(),
                sourcePage.getPage(),
                sourcePage.getSize(),
                records
        );
    }
}
